﻿using UnityEngine;
using System.Collections;
using System.Xml;

public class Serialization : MonoBehaviour {
    [AddComponentMenu("SerializeScenes")]

    public GameObject[] serializableObj;
    public string xmlPath;
    private XmlDocument xmlDoc;
	void Start () {
        xmlPath = Application.dataPath + "/serializationXML.xml"; // 注意名字前要有斜杠
        xmlDoc = new XmlDocument();
	}

    public void Serialize()
    {
        XmlElement root = xmlDoc.CreateElement("SerializableScene");

        // Serialize Obj;
        foreach (GameObject obj in serializableObj)
        {
            try
            {
                XmlElement objNode = xmlDoc.CreateElement(obj.name);
                objNode.SetAttribute("PrefabName", obj.name);   // Type should be replaced by some mechanism that could identify the Obj prefab name. 
                objNode.SetAttribute("WorldPosition", obj.transform.position.x + "," + obj.transform.position.y + "," + obj.transform.position.z + ",");
                objNode.SetAttribute("Scale", obj.transform.localScale.x + "," + obj.transform.localScale.y + "," + obj.transform.localScale.z + ",");
                objNode.SetAttribute("Rotation", obj.transform.rotation.x + "," + obj.transform.rotation.y + "," + obj.transform.rotation.z + ",");
                root.AppendChild(objNode);
            }
            catch (UnityException e)
            {
                Debug.LogError("Error!");
            }
        }

        xmlDoc.AppendChild(root);
        xmlDoc.Save(xmlPath);
    }

    public void Deserialze()
    {
        xmlDoc.Load(xmlPath);

        XmlNode root = xmlDoc.FirstChild;

        foreach (XmlElement e in root)
        {
            GameObject g = GameObject.Instantiate<GameObject>( Resources.Load<GameObject>(e.Attributes["PrefabName"].Value));
            string pos = e.Attributes["WorldPosition"].Value;
            g.transform.position = String2Vector3(ref pos);
            string rot = e.Attributes["Rotation"].Value;
            g.transform.localScale = String2Vector3(ref rot);
            string scl = e.Attributes["Scale"].Value;
            g.transform.localScale = String2Vector3(ref scl);
        }
    }
    static public Vector3 String2Vector3(ref string str)
    {
        int i = 0, j = 0, k = 0;
        float[] d = new float[3];

        for (; i < str.Length && k < 3; ++i)
        {
            if (str[i] == ',' && i > j)
            {
                float.TryParse(str.Substring(j, i - j), out d[k]);
                j = i + 1;
                ++k;
            }
        }

        return new Vector3(d[0], d[1], d[2]);
    }
	
}
